'use strict';
const Service = require('egg').Service;
const mongoose = require('mongoose');

/*
 * events: 用于rrweb回放的数据
 * id: 用来区分数据，同一个id可以多次保存
 */
class UseRrwebService extends Service {
  async save(events, id) {
    console.log(`${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} service/rrweb.js save`);
    const {
      ctx,
    } = this;
    console.log('id:');
    console.log(id);
    let result;
    try {
      const hasEvent = await ctx.model.Event.findOne({
        id,
      });
      if (hasEvent) {
        console.log(`同一个id 已经存在的数据 id:${id}`);
        // console.log(hasEvent);
        const oldEvents = JSON.parse(hasEvent.events).events;
        console.log('已经在库里的 event.length:');
        console.log(oldEvents.length);
        events = oldEvents.concat(JSON.parse(events).events);
        console.log('concat 之后的 event.length');
        console.log(events.length);
        events = JSON.stringify({
          events,
        });
        result = await ctx.model.Event.updateOne({
          _id: mongoose.Types.ObjectId(hasEvent._id),
        }, {
          events,
          id,
        });
      } else {
        result = await ctx.model.Event.create({
          events,
          id,
        });
      }
      console.log('result:');
      console.log(result);
      return result;
    } catch (e) {
      return {
        message: e,
        info: '失败',
      };
    }

  }
}

module.exports = UseRrwebService;
